<template>
  <div id="mail">
    <!-- 用户管理 -->
    <div style="width: 15%; position: relative; float: left; padding: 10px" v-if="cities.length != 0">
      <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
        全选
      </el-checkbox>
      <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="city in cities" :key="city.name" :label="city.name" :value="city">
          {{ city.name }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
    <div style="position: relative;width: 100%;overflow: auto;">
      <div style="padding: 5px 0">
        <!-- <el-text class="mx-1" style="margin: 0 15px">关键词：</el-text>
          <el-input v-model="inputKeyWord" style="width: 200px" placeholder="请输入关键词" /> -->
        <!-- <el-text class="mx-1" style="margin: 0 15px">用户名：</el-text> -->
        <el-input v-model="inputKeyWord" style="width: 200px" placeholder="请输入用户名查询" />
        <!-- <el-button type="primary" plain style="margin: 0 15px" @click="searchKeyWord">检索</el-button> -->
      </div>
      <!-- 角色管理 -->
      <el-table :data="tableData" style="margin-bottom: 10px" row-key="id" border default-expand-all stripe>
        <el-table-column prop="id" label="编号" sortable />
        <el-table-column prop="name" label="用户名" sortable />
        <el-table-column prop="username" label="登陆名称" sortable />

        <el-table-column prop="departmentName" label="部门名称" sortable />
        <el-table-column prop="roleName" label="角色名称" sortable />
        <el-table-column prop="phone" label="电话" sortable />
        <el-table-column prop="email" label="邮箱" sortable />

        <!-- <el-table-column prop="status" label="启用状态" sortable>
            <template #default="{ row }">
              <el-switch style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" v-model="row.status" :active-value="1"
                :inactive-value="0" size="" active-text="正常" inactive-text="禁用" inline-prompt />
            </template>
</el-table-column> -->
        <!-- 操作 -->
        <el-table-column label="操作" width="90">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEditShow(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
        :page-sizes="[5, 10, 15, 20]" layout="sizes, prev, pager, next" />
    </div>
  </div>
  <el-dialog v-model="dialogVisible" title="新增用户" width="400" :before-close="handleClose" draggable>
    <el-form :inline="true" :model="formInline" class="demo-form-inline" label-width="auto">
      <el-form-item label="用户名">
        <el-input v-model="formInline.name" placeholder="输入真实姓名" clearable />
      </el-form-item>
      <el-form-item label="登录名称">
        <el-input v-model="formInline.username" placeholder="输入登录账号" clearable />
      </el-form-item>
      <el-form-item label="登录密码">
        <el-input v-model="formInline.password" placeholder="输入登录密码" clearable />
      </el-form-item>
      <el-form-item label="部门名称" v-if="cities.length != 0">
        <el-select v-model="formInline.departId" placeholder="选择部门" clearable>
          <!-- <el-option label="Zone one" value="shanghai" />
            <el-option label="Zone two" value="beijing" /> -->
          <el-option v-for="item in cities" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色名称">
        <el-select v-model="formInline.roleId" placeholder="选择角色" clearable>
          <!-- <el-option label="超级管理员" value="超级管理员" />
            <el-option label="部门管理员" value="部门管理员" />
            <el-option label="普通员工" value="普通员工" /> -->

          <el-option v-for="item in roles" :key="item.id" :label="item.name"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="formInline.phone" placeholder="输入电话" clearable />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="formInline.email" placeholder="输入邮箱" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">
          添加
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogEdit" title="编辑用户" width="400" :before-close="handleClose" draggable>
    <el-form :inline="true" :model="formEdit" class="demo-form-inline" label-width="auto">
      <el-form-item label="用户名">
        <el-input v-model="formEdit.name" placeholder="输入真实姓名" disabled />
      </el-form-item>
      <el-form-item label="登录名称">
        <el-input v-model="formEdit.username" placeholder="输入登录账号" disabled />
      </el-form-item>
      <el-form-item label="部门名称" v-if="cities.length != 0">
        <el-select v-model="formEdit.departId" placeholder="选择部门" disabled>
          <el-option v-for="item in cities" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色名称">
        <el-select v-model="formEdit.roleId" placeholder="选择角色" disabled>
          <el-option v-for="item in roles" :key="item.id" :label="item.name"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="formEdit.phone" placeholder="输入电话" clearable />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="formEdit.email" placeholder="输入邮箱" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogEdit = false">取消</el-button>
        <el-button type="primary" @click="handleEdit">
          修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted, computed, reactive } from "vue";
import { getAllDepartment, getAllUser, addUser, searchAllRoles, editUser } from "@/network/net.js";

let token = sessionStorage.getItem("token");

onMounted(() => {
  initAllDepartment()
  initAllUser()
  initAllRoles()
})

const dialogVisible = ref(false);
const formInline = reactive({
  name: "",
  username: "",
  password: "",
  departId: "",
  roleId: "",
})

const dialogEdit = ref(false);
const formEdit = reactive({
  id: "",
  name: "",
  username: "",
  password: "",
  departId: "",
  roleId: "",
})
const handleAdd = () => {
  dialogVisible.value = false;
  addUser(token, formInline).then((res) => {
    if (res?.data?.code == "200") {
      initAllUser()
    }
  });
};

const handleEditShow = (item) => {

  dialogEdit.value = true;
  formEdit.id = item.id;
  formEdit.name = item.name;
  formEdit.username = item.username;
  formEdit.password = item.password;
  formEdit.departId = item.departId;
  formEdit.roleId = item.role.id;
  formEdit.phone = item.phone;
  formEdit.email = item.email;
}
const handleEdit = () => {
  dialogEdit.value = false;
  editUser(token, formEdit).then((res) => {
    if (res?.data?.code == "200") {
      initAllUser()
    }
  });
}
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
// 当前选中的节点 ID
const selectedNode = ref(null);
const handleNodeClick = (data, node) => {
  selectedNode.value = data.id;
  // 阻止默认行为，即阻止节点折叠
  node.expand();
};
const expandedkeys = ref([]);
const checkedkeys = ref([]);
const defaultProps = {
  children: "children",
  label: "name",
};
const treeData = ref();
treeData.value = [
  {
    id: "all",
    name: "暂无分部门信息",
    children: [],
  },
];

const initAllDepartment = () => {
  getAllDepartment(token).then((res) => {
    if (res?.data?.code == "200" && res?.data?.data?.length > 0) {
      // let arr = res?.data?.data;
      let arr = res?.data?.data.filter((item) => item.status != 0);
      cities.value = arr;
      checkedCities.value = arr;

    } else {
      cities.value = []
      checkedCities.value = []
    }
  });
};

const roles = ref([]);
// searchAllRoles
const initAllRoles = () => {
  searchAllRoles(token).then((res) => {
    if (res?.data?.code == "200" && res?.data?.data?.length > 0) {
      let arr = res?.data?.data;
      roles.value = arr;

    } else {
      roles.value = []
    }
  });
};
const tableData = ref([]);

const initAllUser = () => {
  const departmentName = checkedCities.value.map(item => item.name).join(',')

  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    departmentNames: departmentName,
    username: inputKeyWord.value ? inputKeyWord.value : null,
    name: null
  }

  tableData.value = []
  // if(departmentName == '') {
  //   return
  // }
  getAllUser(token, params).then((res) => {
    total.value = res?.data?.data?.total;
    if (res?.data?.code == "200" && res?.data?.data?.records.length > 0) {
      let arr = res?.data?.data?.records;

      // arr根据id排序
      arr.sort((a, b) => {
        return a.id - b.id;
      });

      arr.map((item) => {
        item.departmentName = item.department.name;
        item.roleName = item.role.name;
        item.pw = "********";
        return item;
      });
      tableData.value = arr;

    }
  });
}


const checkAll = ref(true)
const isIndeterminate = ref(false)
const checkedCities = ref([])
const cities = ref([])

const handleCheckAllChange = (val) => {
  checkedCities.value = val ? cities.value : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === cities.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < cities.value.length
}
// 根据checkedCities筛选tableData
const tableDataComputed = computed(() => {
  const departmentArr = checkedCities.value.map(item => item.name)
  return tableData.value.filter(item => departmentArr.includes(item.departmentName))
})

const inputKeyWord = ref('')

watch([currentPage, inputKeyWord, checkedCities, pageSize], () => {
  initAllUser()
})

</script>
<style lang="less" scoped>
#mail {
  display: flex;
  flex-direction: row;
  width: 100%;
  overflow: auto;
  padding: 5px;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  // font-size: 16px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>